package com.jn.erp.web.api.student.controller;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.jn.erp.common.annotation.Log;
import com.jn.erp.common.core.page.TableDataInfo;
import com.jn.erp.common.core.result.AjaxResult;
import com.jn.erp.security.controller.BaseWebAuthController;
import com.jn.erp.web.api.course.entity.dto.*;
import com.jn.erp.web.api.course.entity.vo.DataTrendsVo;
import com.jn.erp.web.api.course.entity.vo.TCourseOrderVo;
import com.jn.erp.web.api.student.entity.StudentCourse;
import com.jn.erp.web.api.student.entity.TStudentCourseSale;
import com.jn.erp.web.api.student.entity.dto.DataTrendsOrderExcalDto;
import com.jn.erp.web.api.student.entity.dto.DataTrendsOrderSaleExcalDto;
import com.jn.erp.web.api.student.entity.dto.TStudentCourseDto;
import com.jn.erp.web.api.student.entity.dto.TStudentCourseExcelDto;
import com.jn.erp.web.api.student.entity.vo.StudentCourseVo;
import com.jn.erp.web.api.student.entity.vo.TStudentCourseVo;
import com.jn.erp.web.api.student.entity.vo.TransferOrderVo;
import com.jn.erp.web.api.student.service.StudentCourseService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * <p>
 * 报名签约表 前端控制器
 * </p>
 *
 * @author wyp
 * @since 2024-09-29
 */
@RestController
@RequestMapping("/tStudentCourse")
public class TStudentCourseController  extends BaseWebAuthController {

    @Autowired
    private StudentCourseService studentCourseService;
    /**
     * 学员报名
     */
    @PostMapping("/application")
    public AjaxResult application(@RequestBody StudentCourseVo studentCourseVo) {
       //机构id
       studentCourseVo.setOrgId(Long.parseLong(loginDeptAuth()) );
       //当前登录人id
       studentCourseVo.setCreator(getUserId());
        String code = studentCourseService.application(studentCourseVo,true);
        return AjaxResult.success(code);
    }

    /**
     * 订单列表
     */
    @GetMapping("/list")
    public TableDataInfo list( TStudentCourseVo tStudentCourseVo) {
        startPage();
        //机构id
        tStudentCourseVo.setOrgId(Long.parseLong(loginDeptAuth()) );
        //当前登录人id
//        tStudentCourseVo.setCreator(getUserId());
        List<TStudentCourseDto> list = studentCourseService.studentCourseList(tStudentCourseVo);
        return getDataTable(list);
    }

    /**
     * 订单详情
     */
    @PostMapping("/detail")
    public AjaxResult detail(@RequestBody TStudentCourseVo tStudentCourseVo) {

        //机构id
        tStudentCourseVo.setOrgId(Long.parseLong(loginDeptAuth()) );
        //当前登录人id
        tStudentCourseVo.setCreator(getUserId());
        TStudentCourseDto tStudentCourseDto = studentCourseService.studentCourseDetail(tStudentCourseVo);
        return AjaxResult.success(tStudentCourseDto);
    }


    /**
     * 业绩归属人
     */
    @PostMapping("/salerList")
    public AjaxResult salerList(@RequestBody TStudentCourseVo tStudentCourseVo) {

        //机构id
        tStudentCourseVo.setOrgId(Long.parseLong(loginDeptAuth()) );
        //当前登录人id
        tStudentCourseVo.setCreator(getUserId());
        List<TStudentCourseSale> tStudentCourseSales = studentCourseService.salerList(tStudentCourseVo);
        return AjaxResult.success(tStudentCourseSales);
    }

    //导出--订单
    @RequestMapping("/exportOrderList")
    public void exportOrderList(@RequestBody TStudentCourseVo tStudentCourseVo, HttpServletResponse response){
        //机构id
        tStudentCourseVo.setOrgId(Long.parseLong(loginDeptAuth()) );
        //当前登录人id
        tStudentCourseVo.setCreator(getUserId());
        //1.查询数据
        List<TStudentCourseDto> tStudentCourseDtos = studentCourseService.studentCourseList(tStudentCourseVo);

        List<TStudentCourseExcelDto> tStudentCourseExcelDtos = tStudentCourseDtos.stream().map(u->{
            TStudentCourseExcelDto t = new TStudentCourseExcelDto();
            BeanUtils.copyProperties(u,t);
            return t;
        }).collect(Collectors.toList());
        AtomicInteger i = new AtomicInteger(1);

        //2.封装成表格
        //参数1：表格标题，参数2：sheet名称
        ExportParams exportParams = new ExportParams(null, "订单导出");


        //参数1：表格参数  参数2：实体类  参数3：数据
        Workbook sheets = ExcelExportUtil.exportExcel(exportParams, TStudentCourseExcelDto.class, tStudentCourseExcelDtos);
        //3.返回表格
        //设置表格文件名字
        String fileName = "订单导出";
        try {
            fileName = URLEncoder.encode(fileName, "UTF8");
            //设置返回数据类型
            response.setHeader("Access-Control-Expose-Headers", "content-disposition");
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");

            //将表格输出
            OutputStream os = response.getOutputStream();
            sheets.write(os);
            os.close();
            os.flush();
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 学生报读过得课程
     */
    @PostMapping("/courseList")
    public AjaxResult courseList(@RequestBody TStudentCourseVo tStudentCourseVo) {

        //机构id
        tStudentCourseVo.setOrgId(Long.parseLong(loginDeptAuth()) );
        //当前登录人id
        tStudentCourseVo.setCreator(getUserId());
        List<TStudentCourseDto>  tStudentCourseDtos = studentCourseService.courseList(tStudentCourseVo);
        return AjaxResult.success(tStudentCourseDtos);
    }

    /**
     * 学生报读过得课程的订单列表
     */
    @PostMapping("/courseOrderList")
    public AjaxResult courseOrderList(@RequestBody TStudentCourseVo tStudentCourseVo) {

        //机构id
        tStudentCourseVo.setOrgId(Long.parseLong(loginDeptAuth()) );
        //当前登录人id
        tStudentCourseVo.setCreator(getUserId());
        List<TStudentCourseDto>  tStudentCourseDtos = studentCourseService.courseOrderList(tStudentCourseVo);
        return AjaxResult.success(tStudentCourseDtos);
    }

    /**
     * 退课
     */
    @PostMapping("/refundOrder")
    public AjaxResult refundOrder(@RequestBody List<TStudentCourseVo> tStudentCourseVos) {
        tStudentCourseVos.stream().forEach(u->{
            //机构id
            u.setOrgId(Long.parseLong(loginDeptAuth()) );
            //当前登录人id
            u.setEditor(getUserId());
        });

        String  code = studentCourseService.refundOrder(tStudentCourseVos,"订单处理-退课");
        return AjaxResult.success(code);
    }


    /**
     * 转课
     */
    @PostMapping("/transferOrder")
    public AjaxResult transferOrder(@RequestBody TransferOrderVo transferOrderVo) {
        List<TStudentCourseVo> tStudentCourseVos = transferOrderVo.gettStudentCourseVos();
        for (TStudentCourseVo u : tStudentCourseVos) {
            //机构id
            u.setOrgId(Long.parseLong(loginDeptAuth()) );
            //当前登录人id
            u.setEditor(getUserId());
        }

        StudentCourseVo studentCourseVo = transferOrderVo.getStudentCourseVo();
        //机构id
        studentCourseVo.setOrgId(Long.parseLong(loginDeptAuth()) );
        //当前登录人id
        studentCourseVo.setCreator(getUserId());
        String  code = studentCourseService.transferOrder(transferOrderVo);
        return AjaxResult.success(code);
    }


    /**
     * 清零
     */
    @PostMapping("/update")
    public AjaxResult update(@RequestBody TStudentCourseVo tStudentCourseVo) {

        //机构id
        tStudentCourseVo.setOrgId(Long.parseLong(loginDeptAuth()) );
        //当前登录人id
        tStudentCourseVo.setEditor(getUserId());
        tStudentCourseVo.setEditTime(LocalDateTime.now());

        studentCourseService.updateStudentCourse(tStudentCourseVo);
        return AjaxResult.success("S200");
    }


    /**
     * 结课
     */
    @PostMapping("/classEnding")
    public AjaxResult classEnding(@RequestBody TStudentCourseVo tStudentCourseVo) {

        //机构id
        tStudentCourseVo.setOrgId(Long.parseLong(loginDeptAuth()) );
        //当前登录人id
        tStudentCourseVo.setEditor(getUserId());
        tStudentCourseVo.setEditTime(LocalDateTime.now());

        studentCourseService.classEnding(tStudentCourseVo);
        return AjaxResult.success("S200");
    }


    /**
     * 停课，复课
     */
    @PostMapping("/stopsAndResume")
    public AjaxResult stopsAndResume(@RequestBody TStudentCourseVo tStudentCourseVo) {

        //机构id
        tStudentCourseVo.setOrgId(Long.parseLong(loginDeptAuth()) );
        //当前登录人id
        tStudentCourseVo.setEditor(getUserId());
        tStudentCourseVo.setEditTime(LocalDateTime.now());

        studentCourseService.stopsAndResume(tStudentCourseVo);
        return AjaxResult.success("S200");
    }

    /**
     * 实际总收入
     */
    @PostMapping("/sumAmount")
    public AjaxResult sum(@RequestBody TStudentCourseVo tStudentCourseVo) {

        //机构id
        tStudentCourseVo.setOrgId(Long.parseLong(loginDeptAuth()) );
        //当前登录人id
        tStudentCourseVo.setEditor(getUserId());
        tStudentCourseVo.setEditTime(LocalDateTime.now());

        BigDecimal bigDecimal = studentCourseService.sumAmount(tStudentCourseVo);
        return AjaxResult.success(bigDecimal);
    }

    /**
     * 学员内报读课程
     */
    @PostMapping("/listSecond")
    public AjaxResult listSecond(@RequestBody TStudentCourseVo tStudentCourseVo) {

        //机构id
        tStudentCourseVo.setOrgId(Long.parseLong(loginDeptAuth()) );
        //当前登录人id
        tStudentCourseVo.setEditor(getUserId());
        tStudentCourseVo.setEditTime(LocalDateTime.now());

        List<TStudentCourseDto> list = studentCourseService.listSecond(tStudentCourseVo);
        return AjaxResult.success(list);
    }

    /**
     *超上处理
     */
    @PostMapping("/dealExceed")
    public AjaxResult dealExceed(@RequestBody TStudentCourseVo tStudentCourseVo) {

        //机构id
        tStudentCourseVo.setOrgId(Long.parseLong(loginDeptAuth()) );
        //当前登录人id
        tStudentCourseVo.setEditor(getUserId());
        tStudentCourseVo.setEditTime(LocalDateTime.now());

        String code = studentCourseService.dealExceed(tStudentCourseVo);
        return AjaxResult.success(code);
    }

    /**
     * 财务数据-核心数据
     * */
    @PostMapping("/countAcademicData")
    public AjaxResult countAcademicData(@RequestBody DataTrendsVo dataTrendsVo) {


        //机构id
        dataTrendsVo.setOrgId(Long.parseLong(loginDeptAuth()) );
        //当前登录人id
        dataTrendsVo.setCreator(getUserId() );

        Map map = studentCourseService.countAcademicData(dataTrendsVo);
        return AjaxResult.success(map);
    }

    /**
     * 财务数据-数据趋势
     * */
    @GetMapping("/dataTrends")
    public TableDataInfo dataTrends(DataTrendsVo dataTrendsVo) {
        startPage();

        //机构id
        dataTrendsVo.setOrgId(Long.parseLong(loginDeptAuth()) );
        //当前登录人id
        dataTrendsVo.setCreator(getUserId() );

        List<DataTrendsDto> dataTrends = studentCourseService.dataTrends(dataTrendsVo);
        return getDataTable(dataTrends);
    }

    /**
     * 财务数据-业绩归属
     * */
    @GetMapping("/dataTrendsSale")
    public TableDataInfo dataTrendsSale(DataTrendsVo dataTrendsVo) {
        startPage();

        //机构id
        dataTrendsVo.setOrgId(Long.parseLong(loginDeptAuth()) );
        //当前登录人id
        dataTrendsVo.setCreator(getUserId() );

        List<DataTrendsDto> dataTrends = studentCourseService.dataTrendsSale(dataTrendsVo);
        return getDataTable(dataTrends);
    }

    /**
     * 财务数据-数据趋势-图表特定格式
     * */
    @PostMapping("/dataTrendsEChart")
    public AjaxResult dataTrendsEChart(@RequestBody DataTrendsVo dataTrendsVo) {


        //机构id
        dataTrendsVo.setOrgId(Long.parseLong(loginDeptAuth()) );
        //当前登录人id
        dataTrendsVo.setCreateUser(String.valueOf(getUserId()) );

        Map<String, List<List>>  dataTrends = studentCourseService.dataTrendsEChart(dataTrendsVo);
        return AjaxResult.success(dataTrends);
    }

    //导出--点名情况--上课记录列表分班级学员
    @RequestMapping("/exportdataTrend")
    public void exportdataTrend(@RequestBody DataTrendsVo dataTrendsVo, HttpServletResponse response){
        //机构id
        dataTrendsVo.setOrgId(Long.parseLong(loginDeptAuth()) );
        //当前登录人id
        dataTrendsVo.setCreateUser(String.valueOf(getUserId()) );
        Workbook sheets = null;
        if(StringUtils.isEmpty(dataTrendsVo.getExportType())){
            dataTrendsVo.setExportType("1");
        }
        //3.返回表格
        //设置表格文件名字
        String fileName = "趋势概况";
        //1趋势概况2上课老师报表3班级报表4课程报表5在读学员报表
        switch (dataTrendsVo.getExportType()){
            case "1" :{
                //1.查询数据
                List<DataTrendsDto> dataTrends = studentCourseService.dataTrends(dataTrendsVo);
                List<DataTrendsOrderExcalDto> list = dataTrends.stream().map(u->{
                    DataTrendsOrderExcalDto dataTrendsExcalDto = new DataTrendsOrderExcalDto();
                    BeanUtils.copyProperties(u,dataTrendsExcalDto);
                    return dataTrendsExcalDto;
                }).collect(Collectors.toList());
                AtomicInteger i = new AtomicInteger(1);

                //2.封装成表格
                //参数1：表格标题，参数2：sheet名称
                ExportParams exportParams = new ExportParams(null, "趋势概况");


                //参数1：表格参数  参数2：实体类  参数3：数据
                sheets = ExcelExportUtil.exportExcel(exportParams, DataTrendsOrderExcalDto.class, list);
                fileName = "趋势概况";
                break;
            }
            case "2" :{
                //1.查询数据
                List<DataTrendsDto> dataTrends = studentCourseService.dataTrendsSale(dataTrendsVo);
                List<DataTrendsOrderSaleExcalDto> list = dataTrends.stream().map(u->{
                    DataTrendsOrderSaleExcalDto dataTrendsExcalDto = new DataTrendsOrderSaleExcalDto();
                    BeanUtils.copyProperties(u,dataTrendsExcalDto);
                    return dataTrendsExcalDto;
                }).collect(Collectors.toList());
                AtomicInteger i = new AtomicInteger(1);

                //2.封装成表格
                //参数1：表格标题，参数2：sheet名称
                ExportParams exportParams = new ExportParams(null, "业绩归属");


                //参数1：表格参数  参数2：实体类  参数3：数据
                sheets = ExcelExportUtil.exportExcel(exportParams, DataTrendsOrderSaleExcalDto.class, list);
                fileName = "业绩归属";
                break;
            }
        }


        try {
            fileName = URLEncoder.encode(fileName, "UTF8");
            //设置返回数据类型
            response.setHeader("Access-Control-Expose-Headers", "content-disposition");
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");

            //将表格输出
            OutputStream os = response.getOutputStream();
            sheets.write(os);
            os.close();
            os.flush();
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}

